<template>
  <div class="order-management-panel">
    <!-- 顶部标题区域 -->
    <div class="panel-header">
      <span class="panel-title">
        <el-icon style="margin-right: 8px;"><Document /></el-icon>
        工单管理
      </span>
    </div>
    <el-divider class="custom-divider" />

    <div style="margin-top: 30px;">
      <!-- 操作按钮区域 -->
      <el-row class="operation-row">
        <el-button 
          type="primary" 
          class="idoo-details-add"
          @click="handleDataSync"
        > 
          数据同步 
        </el-button>
        <ExcelImport 
          :import-config="workOrderImportConfig" 
          @import-success="onWorkOrderImportSuccess"
          @import-error="onWorkOrderImportError" 
          style="margin-left: 10px;" 
        />
      </el-row>

      <!-- 待排程工单区域 -->
      <el-row class="section-header">
        <span class="section-title">
          待排程工单（{{ unselectedOrders.length }}）
        </span>
        <!-- 选择按钮 -->
        <el-button 
          v-if="selectedRows.length > 0" 
          link 
          class="custom-link-button" 
          style="margin-left: 20px;"
          @click="addToSelectedOrders"
        >
          选择 ({{ selectedRows.length }})
        </el-button>
      </el-row>

      <!-- 待排程工单表格 -->
      <el-row>
        <IdooAddRowTable 
          ref="unselectedOrderTableRef" 
          :data="unselectedOrders" 
          :columns="unselectedOrderColumns"
          style="margin-top: 10px; min-height: 400px;" 
          @selectionChange="onUnselectedSelectionChange"
          @rowSave="handleRowSave" 
        />
      </el-row>
    </div>

    <el-divider border-style="dotted" />

    <!-- 已选择工单区域 -->
    <div style="margin-top: 20px;">
      <el-row class="section-header">
        <span class="section-title">
          已选择工单（{{ selectedOrders.length }}）
        </span>
        <el-button
          v-if="selectedOrders.length > 0"
          link
          class="custom-link-button"
          style="margin-left: 20px;"
          @click="clearSelectedOrders"
        >
          清空选择
        </el-button>
      </el-row>
      
      <el-row>
        <el-table 
          border 
          :data="selectedOrders" 
          style="margin-top: 10px; min-height: 400px;"
          @selection-change="onSelectedOrdersSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="apsOrderCode" label="工单编号" width="350" />
          <el-table-column prop="orderCode" label="订单编号" width="350" />
          <el-table-column prop="productCode" label="产品编号" width="250" />
          <el-table-column prop="deliveryDate" label="交付日" width="150" />
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="priority" label="优先级" />
        </el-table>
      </el-row>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import IdooAddRowTable from '@/idoo-core/table/add-row-table/IdooAddRowTable.vue'
import ExcelImport from '@/components/common/ExcelImport.vue'
import { orderApi } from '@/api/order'
import {
  unselectedOrderColumns,
  workOrderImportConfig,
  ErrorMessages,
  SuccessMessages
} from '../../views/VisualizationConfig'

export default {
  name: 'OrderManagementPanel',
  components: {
    IdooAddRowTable,
    ExcelImport,
    Document
  },
  props: {
    // 已选择的工单数据
    selectedOrders: {
      type: Array,
      default: () => []
    },
    // 未选择的工单数据
    unselectedOrders: {
      type: Array,
      default: () => []
    },
    // 是否显示加载状态
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: [
    'update-selected-orders', 
    'data-sync-requested', 
    'orders-imported',
    'selection-changed'
  ],
  setup(props, { emit }) {
    console.log('🎯 OrderManagementPanel 接收到的props:', {
      selectedOrdersCount: props.selectedOrders?.length,
      unselectedOrdersCount: props.unselectedOrders?.length,
      loading: props.loading
    })

    // ============== 数据定义 ==============
    const unselectedOrderTableRef = ref(null)
    const selectedRows = ref([])
    const selectedOrdersForDelete = ref([])

    // ============== 方法定义 ==============

    /**
     * 监听待排程工单表格的多选操作
     */
    const onUnselectedSelectionChange = (rows) => {
      selectedRows.value = rows
      console.log('📋 待排程工单选择变化:', {
        selectedCount: rows.length,
        selectedIds: rows.map(row => row.id || row._id)
      })
      
      emit('selection-changed', {
        type: 'unselected',
        selectedCount: rows.length,
        selectedRows: rows
      })
    }

    /**
     * 监听已选择工单表格的多选操作
     */
    const onSelectedOrdersSelectionChange = (rows) => {
      selectedOrdersForDelete.value = rows
      console.log('📋 已选择工单选择变化:', {
        selectedCount: rows.length,
        selectedIds: rows.map(row => row.id || row._id)
      })
    }

    /**
     * 处理表格行保存事件
     */
    const handleRowSave = (row, index, callback) => {
      console.log('💾 保存工单行数据:', { row, index })
      
      // 验证必填字段
      const requiredFields = [
        { prop: 'orderCode', label: '订单编号' },
        { prop: 'productCode', label: '产品编号' },
        { prop: 'deliveryDate', label: '交付日' },
        { prop: 'quantity', label: '数量' },
        { prop: 'priority', label: '优先级' }
      ]

      for (const field of requiredFields) {
        if (!row[field.prop] || row[field.prop] === '') {
          ElMessage.warning(`请填写${field.label}`)
          callback({ success: false })
          return
        }
      }

      // 如果是新增行，生成工单编号
      if (row.isNew && !row.apsOrderCode) {
        row.apsOrderCode = `W-${Date.now()}`
        row._id = `${row.apsOrderCode}-${row.orderCode}`
      }

      console.log('✅ 工单数据保存成功:', row)
      ElMessage.success(SuccessMessages.ROW_SAVED)
      
      // 通知表格组件保存成功
      callback({ success: true })
    }

    /**
     * 点击"选择"按钮，将勾选的工单移动到已选工单列表
     */
    const addToSelectedOrders = async () => {
      console.log('🔄 开始添加工单到已选列表...')
      
      // 1) 先检查表格是否还有正在编辑的行
      const allRows = unselectedOrderTableRef.value?.getAllData() || []
      if (allRows.some(row => row.isEditing)) {
        ElMessage.warning(ErrorMessages.SAVE_EDITING_ROW)
        return
      }

      // 2) 调用表格的验证方法
      const valid = await unselectedOrderTableRef.value.validate()
      if (!valid) {
        return
      }

      // 3) 获取选中的数据
      const selected = unselectedOrderTableRef.value?.getSelectedData() || []
      if (selected.length === 0) {
        ElMessage.warning(ErrorMessages.SELECT_ORDER_FIRST)
        return
      }

      console.log('📤 准备提交选中的工单:', {
        count: selected.length,
        orders: selected.map(order => ({
          id: order.id || order._id,
          orderCode: order.orderCode,
          productCode: order.productCode
        }))
      })

      // 4) 调用后端接口保存选中的订单
      try {
        const response = await orderApi.selectOrders(selected)
        
        if (response && response.data) {
          console.log('✅ 后端返回工单选择结果:', {
            successCount: response.data.length,
            returnedOrders: response.data.map(order => order.id || order._id)
          })

          // 5) 通知父组件更新工单列表
          const updateData = {
            selectedOrders: [...props.selectedOrders, ...response.data],
            unselectedOrders: props.unselectedOrders.filter(
              item => !response.data.some(selectedItem => 
                (selectedItem.id || selectedItem._id) === (item.id || item._id)
              )
            )
          }
          
          console.log('📡 通知父组件更新工单数据:', {
            newSelectedCount: updateData.selectedOrders.length,
            newUnselectedCount: updateData.unselectedOrders.length
          })
          
          emit('update-selected-orders', updateData)
          
          // 6) 清除表格选中状态
          unselectedOrderTableRef.value?.clearSelection()
          selectedRows.value = []
          
          ElMessage.success(SuccessMessages.ORDERS_SELECTED(response.data.length))
        }
      } catch (error) {
        console.error('❌ 保存订单失败:', error)
        ElMessage.error(ErrorMessages.SAVE_ORDER_FAILED)
      }
    }

    /**
     * 清空已选择的工单
     */
    const clearSelectedOrders = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要清空所有已选择的工单吗？共 ${props.selectedOrders.length} 条`,
          '清空确认',
          {
            type: 'warning',
            confirmButtonText: '确定清空',
            cancelButtonText: '取消'
          }
        )

        console.log('🗑️ 清空已选择工单:', props.selectedOrders.length)
        
        const updateData = {
          selectedOrders: [],
          unselectedOrders: [...props.unselectedOrders, ...props.selectedOrders]
        }

        emit('update-selected-orders', updateData)
        ElMessage.success('已清空所有选择的工单')
      } catch (err) {
        if (err !== 'cancel' && err !== 'close') {
          console.error('清空工单失败:', err)
        }
      }
    }

    /**
     * 数据同步处理
     */
    const handleDataSync = () => {
      console.log('🔄 触发数据同步事件')
      emit('data-sync-requested')
      ElMessage.info('正在同步数据...')
    }

    /**
     * Excel导入成功处理
     */
    const onWorkOrderImportSuccess = (data) => {
      console.log('📊 Excel导入成功:', data)
      ElMessage.success(SuccessMessages.IMPORT_SUCCESS(data.successCount))
      
      emit('orders-imported', {
        type: 'success',
        data: data
      })
    }

    /**
     * Excel导入失败处理
     */
    const onWorkOrderImportError = (error) => {
      console.error('❌ Excel导入失败:', error)
      ElMessage.error(ErrorMessages.IMPORT_FAILED)
      
      emit('orders-imported', {
        type: 'error',
        error: error
      })
    }

    // ============== 返回 ==============
    return {
      // 引用
      unselectedOrderTableRef,
      
      // 数据
      selectedRows,
      selectedOrdersForDelete,

      // 方法
      onUnselectedSelectionChange,
      onSelectedOrdersSelectionChange,
      handleRowSave,
      addToSelectedOrders,
      clearSelectedOrders,
      handleDataSync,
      onWorkOrderImportSuccess,
      onWorkOrderImportError,

      // 常量
      unselectedOrderColumns,
      workOrderImportConfig
    }
  }
}
</script>

<style scoped>
.order-management-panel {
  height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.panel-title {
  color: #409EFF;
  font-size: 24px;
  font-weight: 700;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
  display: flex;
  align-items: center;
}

.operation-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-top: 30px;
  margin-bottom: 10px;
}

.section-title {
  font-weight: 600;
  font-size: large;
  color: rgb(1, 128, 165);
}

.custom-divider {
  margin: 20px 0;
  border-style: dotted;
}

.custom-link-button {
  color: black;
  font-weight: 600;
  cursor: pointer;
  text-decoration: underline;
}

.custom-link-button:hover {
  color: rgb(1, 128, 165);
}

.idoo-details-add {
  background-color: #409EFF;
  border-color: #409EFF;
}
</style>
